package com.mo;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author moon.pan
 * @program mo-all
 * @apiNote
 * @since 2022/3/21
 */
public class CompletableFutureDemo {

    @Test
    public void exception() {

        List<CompletableFuture<Integer>> list = new ArrayList<>();

        for (int i = 10; i >= 0; i--) {
            int finalI = i;
            CompletableFuture<Integer> one = CompletableFuture.supplyAsync(() -> {
                int j = 100 / finalI;
                System.out.println(finalI);
                return j;
            }).exceptionally(ex -> 0);
            list.add(one);
        }

        CompletableFuture<Void> allOf = CompletableFuture.allOf(list.toArray(new CompletableFuture[0]));
        allOf.join();
        System.out.println("666");
    }


    @Test
    public void two() {
        CompletableFuture<Integer> one = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task-1");
            return 0;
        });

        CompletableFuture<Integer> two = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task-1");
            return 0;
        });

        CompletableFuture<Void> allOf = CompletableFuture.allOf(one, two);
        System.out.println("等待任务ing");
//        allOf.join();
        System.out.println("任务结束...");
    }


    @Test
    public void one() {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test");
            return 0;
        });

        System.out.println(66);
    }
}
